package com.hit.client.driver.netty.protocol.encoder;

import com.hit.client.driver.netty.protocol.message.GfMessage;
import com.hit.client.driver.util.GfToolkit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 编码器
 */
@Slf4j
public class GfEncoder extends MessageToByteEncoder<GfMessage> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, GfMessage message, ByteBuf byteBuf) throws Exception {
        byteBuf.writeBytes(GfMessage.head);
        byteBuf.writeByte(message.getLength());
        // 注意这边之前已经处理成小端模式
        byteBuf.writeBytes(message.getData());
        byteBuf.writeByte(message.getCheckSum());
        if (log.isDebugEnabled()) {
            byte[] fullMessage = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, fullMessage);
            String hexMessage = GfToolkit.bytesToHexString(fullMessage);
            // 获取远程地址（IP和端口）
            InetSocketAddress remoteAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
            String ip = remoteAddress.getAddress().getHostAddress();
            int port = remoteAddress.getPort();
            log.debug("[gf] send to [{}:{}]: {} ", ip, port, hexMessage);
        }
    }
}
